import { WarningOutlined } from '@ant-design/icons';
import { Menu, Row } from 'antd';
import notify from 'devextreme/ui/notify';
import React, { useRef, useState } from 'react';
import { history, useModel } from 'umi';
import { DevPopup, LayoutB } from '~/public/cpas-ui';
import AntTabs from '~/public/cpas-ui/components-ui/ant-components/AntTab';
import FullNamePupop from '../components/CommonCpasTable/fullNamePupop';
import './index.less';

import {
  getfindDesignTableName,
  getjudgmentInit,
  getSeekAuditReportTemplate,
  gettableIsVerifyList,
  templateInitApi,
} from './service';

const AuditMergeHistory: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const { dbname, sjxmbh, zcbfid, sjnd, XMType, bsdw } = initialState?.curPart;
  const tabRef: any = useRef(null);
  const refsDelte = useRef<any>(1);
  const refsCommonCpasTable = useRef<any>(null);
  const refFullNamePupop = useRef<any>();
  const [isRerun, setIsRerun] = useState(false);
  const [tabText1, setTabText1] = useState('');
  const [activeKey, setActiveKey] = useState('1');
  const [currentMenuKey, setCurrentMenuKey] = useState('1');
  const [spinLoad, setSpinLoad] = useState<boolean>(false);
  const [spinAntTabs, setSpinAntTabs] = useState<boolean>(true);
  const [isInitBtn, setIsInitBtn] = useState<boolean>(true);
  const [valIndex, setValIndex] = useState<string>('1');
  const [hideAddBtn, setHideAddBtn] = useState<boolean>(false);

  const oneLevelItem = [
    {
      key: 1,
      label: '历史合并记录1',
    },
    {
      key: 2,
      label: '历史合并记录2',
    },
    {
      key: 3,
      label: '历史合并记录3',
    },
  ];
  const [antTabsData, setAntTabsData] = useState<any[]>([
    {
      tabName: '资产',
      tabKey: '1',
      isVerify: false,
      closable: false,
      propsData: {
        tableName: '审定财务-资产表',
        titleName: '资产负债表',
        WscwbbType: '资产类',
        origin: '审定财务',
        tabsIndex: 1,
      },
    },
    {
      tabName: '负债',
      tabKey: '2',
      isVerify: false,
      closable: false,
      propsData: {
        tableName: '审定财务-负债表',
        titleName: '资产负债表（续）',
        WscwbbType: '负债类',
        origin: '审定财务',
        tabsIndex: 2,
      },
    },
    {
      tabName: '利润',
      tabKey: '3',
      isVerify: false,
      closable: false,
      propsData: {
        tableName: '审定财务-利润表',
        titleName: '利润表',
        WscwbbType: '利润类',
        origin: '审定财务',
        tabsIndex: 3,
      },
    },
    {
      tabName: '现流',
      tabKey: '4',
      isVerify: false,
      closable: false,
      propsData: {
        tableName: '审定财务-现金流量表',
        titleName: '现金流量表',
        WscwbbType: '现金流量类',
        origin: '审定财务',
        tabsIndex: 4,
      },
    },
    {
      tabName: '现流附',
      tabKey: '5',
      isVerify: false,
      closable: false,
      propsData: {
        tableName: '审定财务-现金流补充资料表',
        titleName: '现金流量表补充资料',
        WscwbbType: '现金流补充资料类',
        origin: '审定财务',
        tabsIndex: 5,
        actionCol: 2,
      },
    },
    {
      tabName: '权益变动(本年)',
      tabKey: '6',
      isVerify: false,
      closable: false,
      propsData: {
        tableName: '审定财务-所有者权益变动表_本年',
        titleName: '所有者权益变动表',
        WscwbbType: '所有者权益变动表',
        origin: '审定财务',
        tabsIndex: 6,
      },
    },
    {
      tabName: '权益变动(上年)',
      tabKey: '7',
      isVerify: false,
      closable: false,
      propsData: {
        tableName: '审定财务-所有者权益变动表_上年',
        titleName: '所有者权益变动表(续)',
        WscwbbType: '所有者权益变动表(上年)类',
        origin: '审定财务',
        tabsIndex: 7,
      },
    },
  ]);
  let tableNameGroup = [
    '审定财务-资产表',
    '审定财务-负债表',
    '审定财务-利润表',
    '审定财务-现金流量表',
    '审定财务-现金流补充资料表',
    '审定财务-所有者权益变动表_本年',
    '审定财务-所有者权益变动表_上年',
    '审定财务-资产减值准备情况表',
  ];
  const AccountTabsClick = (key: string) => {
    console.log(key, 'key----');
    if (key === '2') {
      setIsRerun(false);
    }
    setTabText1(key);
    setActiveKey(key);
  };
  const ReportTypeList = () => {
    return (
      <div>
        <Menu
          items={oneLevelItem}
          defaultSelectedKeys={[currentMenuKey]}
          onClick={async (e) => {
            await onItemClick(e);
          }}
        />
      </div>
    );
  };
  // 一级侧边栏导航点击事件
  const onItemClick = async (e: any) => {
    setCurrentMenuKey(e.key);
  };

  const changeTabsKey = (val: string) => {
    setIsInitBtn(false);
    setValIndex(val);
    history.push('/ReportSys/auditMergeHistory');
  };
  const onEdit = (
    targetKey: React.MouseEvent | React.KeyboardEvent | string,
    action: 'add' | 'remove',
  ) => {
    if (action === 'add') {
      add();
    } else {
      refsDelte.current.show({
        title: '删除提醒',
        okCallback: () => {
          remove(targetKey);
        },
      });
    }
  };
  const add = async () => {
    if (!refsCommonCpasTable.current) return;
    setIsInitBtn(true); // 重要
    console.log(refsCommonCpasTable.current, '@@@ add');
    getAuditReportTemplate(false, '审定财务-资产减值准备情况表', 'addTabs');
    notify(`添加资产减值标签页，成功！`, 'success', 2000);
  };
  const remove = async (targetKey: any) => {
    // console.log(targetKey);
    // 暂时写死
    await refsCommonCpasTable.current.clearDesignTableName('审定财务-资产减值准备情况表');
    setAntTabsData((item) => {
      let lastIndex: any;
      const tempData = [...item];
      tempData.forEach((pane, i) => {
        if (pane.tabKey === targetKey) {
          lastIndex = i - 1;
        }
      });
      const newData = tempData.filter((pane) => pane.tabKey !== targetKey);

      if (newData.length && valIndex === targetKey) {
        if (lastIndex >= 0) {
          setValIndex(newData[lastIndex].tabKey);
        } else {
          setValIndex(newData[0].tabKey);
        }
      }
      return newData;
    });

    // setExcelParams((item: any) => {
    //     const tempData = [...item];
    //     const newData = tempData.filter(pane => pane.tabKey !== targetKey);
    //     return newData;
    // });

    window.localStorage.setItem(
      `审定财务-资产减值准备情况表-${dbname}`,
      JSON.stringify({
        isADD: false,
      }),
    );
    setHideAddBtn(false);
    notify(`删除资产减值标签页，成功！`, 'success', 2000);
  };

  const getAuditReportTemplate = async (
    isAllInit: boolean,
    yearTableName: any,
    actionTabs: any,
  ) => {
    try {
      const judg = await getjudgmentInit({
        dbname,
        type: 'fs',
        tableRealName: yearTableName,
      });
      if (judg.success) {
        console.log(refsCommonCpasTable.current, '@@@ ');
        if (judg.data?.count_number === 0) {
          setSpinLoad(true);
          const res = await getSeekAuditReportTemplate({
            zcbfid,
          });
          if (res.success) {
            let tempObjs: any = {};
            if (isAllInit) {
              tempObjs = {
                tableNames: tableNameGroup,
              };
            } else {
              tempObjs = {
                tableNames: ['审定财务-资产减值准备情况表'],
                opt: {
                  duplicate: 'cover',
                },
              };
            }
            const resTemp: any = await templateInitApi({
              dbName: dbname,
              templateName: res.data.AuditReportTemplate,
              type: 'fs',
              ...tempObjs,
            });
            setSpinLoad(false);
            if (resTemp.success) {
              notify(`模板初始化成功`, 'success', 2000);
              await getDesignTableName(actionTabs);
              setTimeout(async () => {
                if (!refsCommonCpasTable.current) return;
                await refsCommonCpasTable.current?.CPASInit2(yearTableName, true);
                await antTabsDetail();
              }, 300);
            } else {
              await getDesignTableName(actionTabs);
              setTimeout(async () => {
                if (!refsCommonCpasTable.current) return;
                await refsCommonCpasTable.current.CPASInit2(yearTableName, false);
              }, 300);
              if (res.data.AuditReportTemplate) {
                notify(`${resTemp.msg}`, 'error', 2000);
              } else {
                notify(`请在首页组成部分信息内选择报告模板`, 'warning', 2000);
              }
            }
          }
        } else {
          await getDesignTableName(actionTabs);
          setTimeout(async () => {
            if (!refsCommonCpasTable.current) return;
            await refsCommonCpasTable.current.CPASInit2(yearTableName, false);
            await antTabsDetail();
          }, 300);
        }
        setIsInitBtn(false);
      } else {
        notify(`获取判断是否初始化失败！`, 'error', 2000);
      }
    } catch (error) {
      notify(`获取判断是否初始化失败！`, 'error', 2000);
    }
  };
  const getDesignTableName = async (funType: string) => {
    let indexD = -1;
    indexD = antTabsData.findIndex(
      (item) => item.propsData.tableName === '审定财务-资产减值准备情况表',
    );
    const res = await getfindDesignTableName({
      design_tableName: '审定财务-资产减值准备情况表',
      dbname,
    });
    if (res.success) {
      if (res.data || funType === 'addTabs') {
        if (indexD < 0) {
          setAntTabsData((item) => {
            const newData = [...item];
            newData.push({
              tabName: '减值准备',
              tabKey: '8',
              isVerify: false,
              closable: true,
              propsData: {
                tableName: '审定财务-资产减值准备情况表',
                titleName: '资产减值准备情况表',
                WscwbbType: '资产减值准备情况类',
                origin: '审定财务',
                tabsIndex: 8,
              },
            });
            return newData;
          });
          window.localStorage.setItem(
            `审定财务-资产减值准备情况表-${dbname}`,
            JSON.stringify({
              isADD: true,
            }),
          );
          if (funType === 'addTabs') {
            setValIndex('8');
          }
        }
        setHideAddBtn(true);
      } else {
        if (indexD > 0) {
          remove('8');
        }
      }
    }
  };
  const antTabsDetail = async () => {
    const res = await gettableIsVerifyList({ tableName: '审定财务', dbname, isTid: false });
    if (res.success) {
      if (res.data.length > 0) {
        const tempsName = res.data.map((item: { name: string }) => item.name).join(',') || '';
        setAntTabsData((oldData: any) => {
          const newData = [...oldData];
          newData.forEach((item: any) => {
            const msg = item.propsData.tableName;
            const isName = tempsName.includes(msg);
            item.isVerify = isName;
            return item;
          });
          return newData;
        });
      } else {
        setAntTabsData((oldData: any) => {
          const newData = [...oldData];
          newData.forEach((item: any) => {
            item.isVerify = false;
            return item;
          });
          return newData;
        });
      }
    } else {
      notify(`获取isVerify校验失败！`, 'error', 2000);
    }
  };
  return (
    <div style={{ height: 'calc(100vh - 104px)' }} id="report-page-container">
      <Row align={'middle'} wrap={false} className="report-top-box">
        <div className="report-lf">历史合并</div>
        <div className="report-ri">
          <AntTabs
            tabBarStyle={{ background: '#FFF' }}
            onChange={AccountTabsClick}
            className={'report-analysis-tabs'}
            defaultActiveKey="1"
            ref={tabRef}
            activeKey={activeKey}
          >
            <AntTabs.Panel tab="审定财务报表" key="1"></AntTabs.Panel>
            <AntTabs.Panel className={'art-count-panel'} tab="附注与分析" key="2"></AntTabs.Panel>
          </AntTabs>
        </div>
      </Row>

      <div className={activeKey === '1' ? 'finance-report-wrap' : 'report-wrap'}>
        <LayoutB
          rowSize={['10%', '150px', '90%']}
          leftSlot={<ReportTypeList />}
          rightSlot={
            <div className="trialBalance_whole">
              {}
              {/* <PageLoading
                isOpen={spinLoad}
                isMaskClose={false}
                content={'正在初始化...'}
                width={200}
              /> */}
              {spinAntTabs && (
                <AntTabs
                  defaultActiveKey="1"
                  className="changeTabsHeight"
                  type="editable-card"
                  destroyInactiveTabPane={true}
                  onChange={(val: string) => {
                    changeTabsKey(val);
                  }}
                  activeKey={valIndex}
                  onEdit={onEdit}
                  hideAdd={hideAddBtn}
                >
                  {antTabsData.map((item) => (
                    <AntTabs.TabPane
                      tab={
                        // <div onDoubleClick={() => handleDoubleClick(item.propsData.tableName, item.tabName)}>
                        <div>
                          <span>
                            {item.tabName}
                            {item.isVerify && (
                              <span
                                className="render-span"
                                onClick={() => {
                                  if (refsCommonCpasTable.current) {
                                    refsCommonCpasTable.current.CPASOpenDetail();
                                  }
                                }}
                              >
                                <WarningOutlined />
                              </span>
                            )}
                          </span>
                        </div>
                      }
                      key={item.tabKey}
                      closable={item.closable}
                    >
                      {/* <CommonCpasTable CPASTableProps={item.propsData} CPASTableTabName={item.tabName}
                                isInitBtn={isInitBtn}
                                changeIsInitBtn={() => {
                                    setIsInitBtn(false);
                                }}
                                biaoAllData={antTabsData}
                                excelParams={excelParams}
                                cpasChangeSpinAntTabs={(data: boolean, yearTableName: any) => { changeSpinAntTabs(data, yearTableName) }} antTabsTabPaneDetail2={() => antTabsDetail()}
                                ref={refsCommonCpasTable}
                                tableNameGroup={tableNameGroup}
                            /> */}
                    </AntTabs.TabPane>
                  ))}
                </AntTabs>
              )}
              <DevPopup.Default ref={refsDelte} width={80} height={220}>
                {() => {
                  return <span>确定要执行此删除操作吗？</span>;
                }}
              </DevPopup.Default>

              <FullNamePupop ref={refFullNamePupop} />
            </div>
          }
        />
      </div>
    </div>
  );
};

export default AuditMergeHistory;
